// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
//var iMaxFilesize = 1048576; // 1MB
var iMaxFilesize = 10485760; // 10MB
var oTimer = 0;
var sResultFileSize = '';

/*$(function(){
	$(".openfile").click(function(){
		//$("#editFileInput").click();
		$("#image_file").click();
	});
	//$("#editFileInput").on("change",function(){
	$("#image_file").on("change",function(){
		//editfileSelected("editFileInput");
		fileSelected();
	});
*/
	/*
	function editgetFileUrl(sourceId){
		var url;
		if (window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1){
			url = window.webkitURL.createObjectURL(document.getElementById(sourceId).files.item(0));
		}else{
			url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
		}
		return url;	
	}
	function editfileSelected(sourceId){
		var url = editgetFileUrl(sourceId);
		$("#editTargetImg").removeClass("img-demo");
		$("#editTargetImg").addClass("img-show");
		$("#editTargetImg").attr("src",url);
		$("#editFileSource").val(url);
	
	}
	*/
//});

function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
    var hr = Math.floor(secs / 3600);
    var min = Math.floor((secs - (hr * 3600))/60);
    var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

    if (hr < 10) {hr = "0" + hr; }
    if (min < 10) {min = "0" + min;}
    if (sec < 10) {sec = "0" + sec;}
    if (hr) {hr = "00";}
    return hr + ':' + min + ':' + sec;
};

function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

function fileSelected() {

    // hide warnings
    document.getElementById('errorMsg').style.display = 'none';
    document.getElementById('proBar').style.display = 'none';
    document.getElementById('errorFormMsg').style.display = 'none';

    // get selected file element
    var oFile = document.getElementById('image_file').files[0];

    // filter for image files
    var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
    if (! rFilter.test(oFile.type)) {
        document.getElementById('errorMsg').style.display = 'block';
        document.getElementById('errorMsg').innerHTML='请传入图片格式！';
        return;
    }

    // little test for filesize
    if (oFile.size > iMaxFilesize) {
        document.getElementById('errorMsg').style.display = 'block';
        document.getElementById('errorMsg').innerHTML='传入图片尺寸太大！';
        return;
    }

    // get preview element
    var oImage = document.getElementById('editTargetImg');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e){
		$("#editTargetImg").removeClass("img-demo");
		$("#editTargetImg").addClass("img-show");
        // e.target.result contains the DataURL which we will use as a source of the image
        oImage.src = e.target.result;

        oImage.onload = function () { // binding onload event

            // we are going to display some custom image information here
            //sResultFileSize = bytesToSize(oFile.size);
            //document.getElementById('fileinfo').style.display = 'block';
            //document.getElementById('editFileSource').value = oFile.name;
            //document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
            //document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
            //document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}

function startUploading() {
    // cleanup all temp states
    iPreviousBytesLoaded = 0;
   // document.getElementById('upload_response').style.display = 'none';
    document.getElementById('errorMsg').style.display = 'none';
    //document.getElementById('proBar').style.display = 'none';
    document.getElementById('proBar').style.display = 'block';
    document.getElementById('errorFormMsg').style.display = 'none';

    //document.getElementById('progress_percent').innerHTML = '';
    var oProgress = document.getElementById('percent');
    oProgress.style.display = 'block';
    oProgress.style.width = '0%';

    // get form data for POSTing
    //var vFD = document.getElementById('upload_form').getFormData(); // for FF3
    var vFD = new FormData(document.getElementById('upload_form')); 
    //这边的一些数据我不知道怎么处理比较好就注释掉了
    vFD.append('category', (document.getElementById('material_category').options[document.getElementById('material_category').selectedIndex]).value);
    vFD.append('name', document.getElementById('material_name').value);
    vFD.append('material', document.getElementById('material_material').value);
    vFD.append('size', document.getElementById('material_x').value + '*' + document.getElementById('material_y').value + '*' + document.getElementById('material_z').value);
    vFD.append('weight', document.getElementById('material_weight').value);
    vFD.append('aperture', document.getElementById('material_aperture').value);
    vFD.append('price', document.getElementById('material_price').value);
    vFD.append('url', document.getElementById('material_url').value);
    vFD.append('description', document.getElementById('material_description').value);

    // create XMLHttpRequest object, adding few event listeners, and POSTing our data
    var oXHR = new XMLHttpRequest();        
    oXHR.upload.addEventListener('progress', uploadProgress, false);
    oXHR.addEventListener('load', uploadFinish, false);
    oXHR.addEventListener('error', uploadError, false);
    oXHR.addEventListener('abort', uploadAbort, false);
    oXHR.open('POST', 'AppWebUpload');
    oXHR.send(vFD);

    // set inner timer
    oTimer = setInterval(doInnerUpdates, 300);
}

function startEditing() {
    // cleanup all temp states
    iPreviousBytesLoaded = 0;
    document.getElementById('errorMsg').style.display = 'none';
    document.getElementById('proBar').style.display = 'block';
    document.getElementById('errorFormMsg').style.display = 'none';

    var oProgress = document.getElementById('percent');
    oProgress.style.display = 'block';
    oProgress.style.width = '0%';

    // get form data for POSTing
    var vFD = new FormData(document.getElementById('upload_form')); 
    //这边的一些数据我不知道怎么处理比较好就注释掉了
    vFD.append('md5', document.getElementById('current_md5').value);
    vFD.append('category', (document.getElementById('material_category').options[document.getElementById('material_category').selectedIndex]).value);
    vFD.append('name', document.getElementById('material_name').value);
    vFD.append('material', document.getElementById('material_material').value);
    vFD.append('size', document.getElementById('material_x').value + '*' + document.getElementById('material_y').value + '*' + document.getElementById('material_z').value);
    vFD.append('weight', document.getElementById('material_weight').value);
    vFD.append('aperture', document.getElementById('material_aperture').value);
    vFD.append('price', document.getElementById('material_price').value);
    vFD.append('url', document.getElementById('material_url').value);
    vFD.append('description', document.getElementById('material_description').value);

    // create XMLHttpRequest object, adding few event listeners, and POSTing our data
    var oXHR = new XMLHttpRequest();        
    oXHR.upload.addEventListener('progress', uploadProgress, false);
    oXHR.addEventListener('load', uploadFinish, false);
    oXHR.addEventListener('error', uploadError, false);
    oXHR.addEventListener('abort', uploadAbort, false);
    oXHR.open('POST', 'AppWebItemEdit');
    oXHR.send(vFD);

    // set inner timer
    oTimer = setInterval(doInnerUpdates, 300);
}

function doInnerUpdates() { // we will use this function to display upload speed
    var iCB = iBytesUploaded;
    var iDiff = iCB - iPreviousBytesLoaded;

    // if nothing new loaded - exit
    if (iDiff == 0)
        return;

    iPreviousBytesLoaded = iCB;
    iDiff = iDiff * 2;
    var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
    var secondsRemaining = iBytesRem / iDiff;

    // update speed info
    var iSpeed = iDiff.toString() + 'B/s';
    if (iDiff > 1024 * 1024) {
        iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
    } else if (iDiff > 1024) {
        iSpeed =  (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
    }

    document.getElementById('speed').innerHTML = iSpeed;
    document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);        
}

function uploadProgress(e) { // upload process in progress
    if (e.lengthComputable) {
        iBytesUploaded = e.loaded;
        iBytesTotal = e.total;
        var iPercentComplete = Math.round(e.loaded * 100 / e.total);
        var iBytesTransfered = bytesToSize(iBytesUploaded);

        document.getElementById('percentNum').innerHTML = iPercentComplete.toString() + '%';
        document.getElementById('percent').style.width = iPercentComplete.toString() + '%';
        //document.getElementById('b_transfered').innerHTML = iBytesTransfered;
        if (iPercentComplete == 100) {
            var oUploadResponse = document.getElementById('percentMsg');
            oUploadResponse.innerHTML = '进行中';
            //oUploadResponse.style.display = 'block';
        }
    } else {
        document.getElementById('percent').innerHTML = 'unable to compute';
    }
}

function uploadFinish(e) { // upload successfully finished
    var oUploadResponse = document.getElementById('percentMsg');
    oUploadResponse.innerHTML = e.target.responseText;
    //oUploadResponse.style.display = 'block';

    document.getElementById('percentNum').innerHTML = '100%';
    document.getElementById('percent').style.width = '100%';
    //document.getElementById('filesize').innerHTML = sResultFileSize;
    document.getElementById('remaining').innerHTML = '| 00:00:00';

    clearInterval(oTimer);
}

function uploadError(e) { // upload error
    document.getElementById('errorFormMsg').style.display = 'block';
    document.getElementById('errorFormMsg').innerHTML='传输过程出现错误，传输失败。';
    clearInterval(oTimer);
}  

function uploadAbort(e) { // upload abort
    document.getElementById('errorFormMsg').style.display = 'block';
    document.getElementById('errorFormMsg').innerHTML='传输中断';
    clearInterval(oTimer);
}

$(function(){
    window.onload=function(){
    //document.getElementById("upload_form").onload=function(){
        num = $("#material_category_num").val();
        if(num){
            //Method 1, failed...
            //document.getElementById("material_category").options[num - 1].selected=true;
            //Method 2, failed...
            //$("#material_category option[value=" + num + "]").prop("selected", "selected")
            //Method 3, succeeded!!!
            for (var i = 0; i < document.getElementById("material_category").options.length; i++) {
                if(document.getElementById("material_category").options[i].value == num){
                    document.getElementById("material_category").options[i].setAttribute('selected', true);
                }
            }
        }
    };
    //window.onreset=function(){
    ////document.getElementById("upload_form").onreset=function(){
    //    num = $("#material_category_num").val();
    //    alert(num);
    //    if(num){
    //        document.getElementById("material_category").options[num - 1].selected=true;
    //    }
    //};
});
